using System;
using System.Configuration;
using System.Collections;
using System.Collections.Specialized;
using System.IO;

using Actions.Connectors;
using Actions.Databases;
using Actions.Security;
using Actions.Usecases;

namespace Actions
{
	/// <summary>
	/// Class for total control
	/// </summary>
	public class Manager
	{
		private static Manager _instance = new Manager();		
		
		private	DatabasesPool _dbp;
		private UsecasesPool _up;		
		private	Document _configuration;
		private string _applicationRoot;
			
		public Document	config
		{
			get
			{
				return _configuration;
			}
		}		
        public static Manager i {
			get {
				return _instance;
			}
		}
		public string root
        {
           get
           {
              return _applicationRoot;
           }
        }
        public UsecasesPool	up
		{
			get
			{
				return _up;
			}
		}		
        public DatabasesPool dbp
		{
			get
			{
				return _dbp;
			}
		}		
        
                
		private Manager()
		{		
			NameValueCollection config = ConfigurationSettings.AppSettings as NameValueCollection;
			_applicationRoot = ".";
			
			if (config != null) {
				foreach (string s in config.Keys) {
					if (0 == String.Compare ("ApplicationRoot", s, true)) {
							_applicationRoot = config[s];
					}
				}				
			}
		
			try {
				_configuration = new Document(_applicationRoot + "/bin/Actions.config");
				_dbp = new DatabasesPool(ref _configuration);
				_up = new UsecasesPool(ref _configuration);
				
				if(_applicationRoot != Directory.GetCurrentDirectory())
					Directory.SetCurrentDirectory(_applicationRoot);			
			} catch (Exception e) {
				error("Manager", e);			
			}
		}

		public void execute(IConnector c)
		{		
			try {
				_dbp.connect();
				try {							
					// Make instance of usecase class & execute it										
					try {
						_up.execute(ref c);
					} catch(Exception e) {
						error("Manager", e);
					};
				} finally {
					_dbp.disconnect();
				}
			} catch (Exception e) {
				error("Manager", e);
			}					
		}
		
		public void reloadConfigFile()
		{
			try {
				_dbp.disconnect();
				
				_configuration = new Document(_applicationRoot + "/bin/Actions.config");
				_dbp = new DatabasesPool(ref _configuration);
				_up = new UsecasesPool(ref _configuration);				
			} catch (Exception e) {
				error("Manager", e);			
			}
		}

		public Database db(string id)
		{
			return _dbp.p[id] as Database;
		}

		public void error(string section, Exception e)
		{
			Console.Write("[" + section + "] " + e + "\n");		
		}

		public void info(string section, string info)
		{
			Console.Write("[" + section + "] " + info + "\n");		
		}
				
	}
}
